package com.example.tys.baseapplication.net_tcp.protocol.tcp.KeepAlive;


import com.example.tys.baseapplication.net_tcp.frame.NettyImpl.tcp.BaseTcpClient;
import com.example.tys.baseapplication.net_tcp.frame.PacketRequest;
import com.example.tys.baseapplication.net_tcp.frame.PacketResponse;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeoutException;

import io.netty.channel.ChannelHandlerContext;

/**
 * 心跳
 * Created by tys on 2019/5/3.
 */

public abstract class TcpClient extends BaseTcpClient<PacketRequest, PacketResponse> {

    @Override
    protected int getReadTimeout() {
        return 60;
    }

    @Override
    protected void readIdle(ChannelHandlerContext ctx) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println(prinTime() + " 心跳维持 & 状态设置:" + getConnectStatus().toString());
                String beatHeart = "@#$%00BF{\"api_version\":\"0.1\",\"from\":\"18782918305\",\"to\":\"\",\"msg_id\":\"ANDBZ-090\"," +
                        "\"msg_class\":\"gw_common\",\"msg_name\":\"gw_heartbeat\",\"msg_type\":\"get\",\"token\":\"3d113e197d4f483ea8f9ed09e5e943fb\"}";
                PacketRequest req = new PacketRequest("ANDBZ-090");
                req.setData(beatHeart.getBytes());
                try {
                    PacketResponse send = send(req, -1);
                } catch (TimeoutException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();

        //1.网络变化监听 ==> 网络可用时(判断连接状态 连接)
        //2.待机，低电耗模式下 ==> 网络断开,后台线程停止  ==> 开屏连接
//        setConnectStatus(ConnectStatus.CONNECT_FAILED);

    }

    private String prinTime() {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return format.format(new Date());
    }


    @Override
    protected void afterReceive(PacketResponse packetResponse) {
        super.afterReceive(packetResponse);
        System.out.println("size：" + mFutureManager.FUTURES_MAP.size());
        System.out.println("==================================================");
    }
}
